package com.yl.chainStore.control.sick

import com.baomidou.mybatisplus.extension.plugins.pagination.Page
import com.yl.chainStore.common.enums.Status
import com.yl.chainStore.common.enums.TypeEnum
import com.yl.chainStore.control.BaseCtrl
import com.yl.chainStore.entity.sick.CustomerSubscribeLog
import com.yl.chainStore.pojo.vo.sick.CustomerSubscribeLogOperationVo
import com.yl.chainStore.pojo.vo.sick.CustomerSubscribeLogSelectVo
import com.yl.chainStore.services.ICustomerInfoService
import com.yl.chainStore.services.IWebCompanyDeptService
import com.yl.chainStore.services.IWebCompanyUserService
import com.yl.chainStore.services.sick.ICustomerSubscribeLogService
import com.yl.chainStore.services.sick.ISickMedicalRecordsService
import com.yl.chainStore.util.getDayAdd
import com.yl.common.control.ResponseBody
import com.yl.common.control.returnSuccess
import com.yl.common.getContext
import com.yl.users.common.annotations.PermsCode
import com.yl.users.entity.CompanyDept
import com.yl.users.pojo.vo.CompanyDeptSelectVo
import com.yl.users.pojo.vo.CompanyUserSelectVo
import com.yl.users.services.ICompanyDeptService
import com.yl.users.services.ICompanyUserService
import org.springframework.transaction.annotation.Transactional
import org.springframework.transaction.interceptor.TransactionAspectSupport
import org.springframework.web.bind.annotation.*
import java.util.*

/**
 * 客户预约
 */
@RestController
@RequestMapping("customer/subscribe")
open class CustomerSubscribeLogController(
	private val iCustomerInfoService: ICustomerInfoService,
	private val iCompanyDeptService: ICompanyDeptService,
	private val iWebCompanyDeptService: IWebCompanyDeptService,
	private val iWebCompanyUserService: IWebCompanyUserService,
	private val iCompanyUserService: ICompanyUserService,
	private val iCustomerSubscribeLogService: ICustomerSubscribeLogService,
	private val iSickMedicalRecordsService: ISickMedicalRecordsService
) : BaseCtrl() {

	/**
	 * 创建一个预约
	 */
	@PostMapping("createSubscribe")
	@Transactional(rollbackFor = [Exception::class])
	@PermsCode("customer:subscribe:add")
	open fun createSubscribe(@RequestBody subscribeLog: CustomerSubscribeLog): ResponseBody {
		val addSubscribeLog = iCustomerInfoService.addSubscribeLog(subscribeLog)
		if (addSubscribeLog.bodyIsError()) {
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly()
			return addSubscribeLog
		}
		val subLogToRecordsDetail = iCustomerSubscribeLogService.subLogToRecordsDetail(subscribeLog)
		if (subLogToRecordsDetail.bodyIsError()) {
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly()
		}
		return subLogToRecordsDetail
	}

	/**
	 * 获取预约详情
	 */
	@GetMapping("getSubscribeById/{id}")
	@Transactional
	open fun getSubscribeById(@PathVariable id: Long): ResponseBody {
		return returnSuccess(iCustomerSubscribeLogService.getById(id))
	}

	/**
	 * 修改预约
	 */
	@PostMapping("updateSubscribe")
	@Transactional(rollbackFor = [Exception::class])
	@PermsCode("sick:subscribe:update")
	open fun updateSubscribe(@RequestBody subscribeLog: CustomerSubscribeLog): ResponseBody {
		val updateInfo = iCustomerSubscribeLogService.updateInfo(subscribeLog)
		if (updateInfo.bodyIsError()) {
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly()
			return updateInfo
		}
		//修改预约的时候 同时修改记录
		val recordsDetail = iSickMedicalRecordsService.updateDetailBySubscribeLog(subscribeLog)
		if(recordsDetail.bodyIsError()){
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly()
			return recordsDetail
		}
		return returnSuccess()
	}

	/**
	 * 获取部门
	 */
	@GetMapping("getDepartmentList")
	@Transactional
	open fun getDepartmentList(): ResponseBody {
		val list = mutableListOf<Map<String, Any>>()
		val companyDeptSelectVo = CompanyDeptSelectVo()
		val page =
			iCompanyDeptService.getSubCompanyDeptPage(Page<CompanyDept>(1, 10), companyDeptSelectVo)
		for (item in page.records) {
			val mutableMapOf = mutableMapOf<String, Any>()
			mutableMapOf["id"] = item.id
			mutableMapOf["name"] = item.name
			list.add(mutableMapOf)
		}
		return returnSuccess(list)
	}

	/**
	 * 获取预约类型
	 */
	@GetMapping("getSubScribeType")
	@Transactional
	open fun getSubScribeType(): ResponseBody {
		val typeList = mutableListOf<Map<String, Any>>()
		typeList.add(TypeEnum.CUSTOMER_SUBSCRIBE_TYPE_NORMAL.getMap())
		typeList.add(TypeEnum.CUSTOMER_SUBSCRIBE_TYPE_UNDETERMINDED.getMap())
		return returnSuccess(typeList)
	}

	/**
	 * 获取预约查询状态
	 */
	@GetMapping("getSubScribeStatusSelect")
	@Transactional
	open fun getSubScribeStatusSelect(): ResponseBody {
		val statusList = mutableListOf<Map<String, Any>>()
		statusList.add(Status.ALL.getMap())
		statusList.add(Status.WAIT_AUDIT.getMap())
		statusList.add(Status.COMPLETE.getMap())
		statusList.add(Status.OUT_TIME.getMap())
		statusList.add(Status.CANCEL.getMap())
		return returnSuccess(statusList)
	}

	/**
	 * 获取预约时长类型
	 */
	@GetMapping("getSubScribeTime")
	@Transactional
	open fun getSubScribeTime(): ResponseBody {
		val typeList = mutableListOf<Map<String, Any>>()
		for(i in 1..56){
			val time = i*15
			val hour = time/60
			val min = time%60
			var show = ""
			if(hour != 0){
				show = hour.toString()+"小时"
			}
			if(min != 0){
				show = show+min.toString()+"分钟"
			}
			typeList.add(timeMap(time, show))
		}
		return returnSuccess(typeList)
	}

	/**
	 * 查询预约列表 日期-列表方式
	 */
	@PostMapping("getSubScribeListByDate")
	@Transactional
//	@PermsCode("customer:user:all:subscribe:list")
	open fun getSubScribeListByDate(@RequestBody vo: CustomerSubscribeLogSelectVo): ResponseBody {
		if (vo.subLogType == null) {
			vo.subLogType = TypeEnum.CUSTOMER_SUBSCRIBE_TYPE_NORMAL
		}
		if(vo.selectStatus == null){
			vo.unStatus = Status.CANCEL
		}
		if (vo.userId == null) {
			//当前用户预约
			val resList = iWebCompanyDeptService.getSubScribeListByDate(vo)
			for(list in resList){
				for(subLog in list){
					iCustomerInfoService.getJoinInfoByCustomerId(subLog.customerId,subLog)
					if(subLog.itemIds != null && subLog.itemIds!!.isNotEmpty()){
						subLog.itemNames = iCustomerSubscribeLogService.getSubscribeItemsByIdsStr(subLog.itemIdsShow!!)
					}
				}
			}
			return returnSuccess(resList)
		} else {
			val subScribeListByDate = iWebCompanyUserService.getSubScribeListByDate(vo.userId!!, vo)
			for(list in subScribeListByDate){
				for(subLog in list){
					iCustomerInfoService.getJoinInfoByCustomerId(subLog.customerId,subLog)
					if(subLog.itemIds != null && subLog.itemIds!!.isNotEmpty()){
						subLog.itemNames = iCustomerSubscribeLogService.getSubscribeItemsByIdsStr(subLog.itemIdsShow!!)
					}
				}
			}
			return returnSuccess(subScribeListByDate)
		}
	}

	/**
	 * 获取自己和自己下级的预约
	 */
	@PostMapping("getSelfSubScribeListByDate")
	@Transactional
	open fun getSelfSubScribeListByDate(@RequestBody vo: CustomerSubscribeLogSelectVo):ResponseBody{
		if (vo.subLogType == null) {
			vo.subLogType = TypeEnum.CUSTOMER_SUBSCRIBE_TYPE_NORMAL
		}
		if (vo.userId == null) {
			val subUserList = iCompanyUserService.getSubUserList(
				getContext().userId, getContext().companyId,
				CompanyUserSelectVo()
			)
			//当前用户预约
			val resList = iWebCompanyUserService.getSubScribeListByDate(getContext().userId, vo)
			for (u in subUserList) {
				//清除之前的查询缓存
				vo.nurseId = null
				vo.doctorId = null
				vo.consultantId = null
				val subLogList = iWebCompanyUserService.getSubScribeListByDate(getContext().userId, vo)
				for ((i, l) in resList.withIndex()) {
					l.addAll(subLogList[i])
				}
			}
			for(list in resList){
				for(subLog in list){
					iCustomerInfoService.getJoinInfoByCustomerId(subLog.customerId,subLog)
				}
			}

			return returnSuccess(resList)
		} else {
			val subScribeListByDate = iWebCompanyUserService.getSubScribeListByDate(vo.userId!!, vo)
			for(list in subScribeListByDate){
				for(subLog in list){
					iCustomerInfoService.getJoinInfoByCustomerId(subLog.customerId,subLog)
				}
			}
			return returnSuccess(subScribeListByDate)
		}
	}

	/**
	 * 医生被预约列表
	 */
	@PostMapping("getSubScribeListByDoctorId")
	@Transactional
	open fun getSubScribeListByDoctorId(@RequestBody vo: CustomerSubscribeLogSelectVo): ResponseBody {
		if (vo.doctorId == null) {
			vo.doctorId = getContext().userId
		}
		val subscribeLogList = iWebCompanyUserService.getSubscribeLogList(vo)
		for(subLog in subscribeLogList){
			iCustomerInfoService.getJoinInfoByCustomerId(subLog.customerId,subLog)
		}
		return returnSuccess(subscribeLogList)
	}

	/**
	 * 医生被预约分页
	 */
	@PostMapping("getSubScribePageByDoctorId")
	@Transactional
	open fun getSubScribePageByDoctorId(@RequestBody vo: CustomerSubscribeLogSelectVo): ResponseBody {
		if (vo.doctorId == null) {
			vo.doctorId = getContext().userId
		}
		val subscribeLogPage = iWebCompanyUserService.getSubscribeLogPage(vo)
		for(subLog in subscribeLogPage.records){
			iCustomerInfoService.getJoinInfoByCustomerId(subLog.customerId,subLog)
		}
		return returnSuccess(subscribeLogPage)
	}

	/**
	 * 护士被预约列表
	 */
	@PostMapping("getSubScribeListByNurseId")
	@Transactional
	open fun getSubScribeListByNurseId(@RequestBody vo: CustomerSubscribeLogSelectVo): ResponseBody {
		if (vo.nurseId == null) {
			vo.nurseId = getContext().userId
		}
		val subscribeLogList = iWebCompanyUserService.getSubscribeLogList(vo)
		for(subLog in subscribeLogList){
			iCustomerInfoService.getJoinInfoByCustomerId(subLog.customerId,subLog)
		}
		return returnSuccess(subscribeLogList)
	}

	/**
	 * 护士被预约分页
	 */
	@PostMapping("getSubScribePageByNurseId")
	@Transactional
	open fun getSubScribePageByNurseId(@RequestBody vo: CustomerSubscribeLogSelectVo): ResponseBody {
		if (vo.nurseId == null) {
			vo.nurseId = getContext().userId
		}
		val subscribeLogPage = iWebCompanyUserService.getSubscribeLogPage(vo)
		for(subLog in subscribeLogPage.records){
			iCustomerInfoService.getJoinInfoByCustomerId(subLog.customerId,subLog)
		}
		return returnSuccess(subscribeLogPage)
	}

	/**
	 * 分院 预约记录
	 */
	@PostMapping("getSubScribeListBySubCompanyId")
	@Transactional
	open fun getSubScribeListBySubCompanyId(@RequestBody vo: CustomerSubscribeLogSelectVo): ResponseBody {
		val subscribeLogList = iWebCompanyDeptService.getSubscribeLogList(vo)
		for(subLog in subscribeLogList){
			iCustomerInfoService.getJoinInfoByCustomerId(subLog.customerId,subLog)
		}
		return returnSuccess(subscribeLogList)
	}

	/**
	 * 分院 明日预约数量
	 */
	@GetMapping("getTomorrowSubScribeCountBySubCompanyId")
	@Transactional
	open fun getTomorrowSubScribeCountBySubCompanyId(): ResponseBody {
		return returnSuccess(
			iWebCompanyDeptService.getSubscribeLogCount(
				CustomerSubscribeLogSelectVo
					(
					day = getDayAdd(Date(), 1)
				)
			)
		)
	}


	/**
	 * 分院 预约记录分页
	 */
	@PostMapping("getSubScribePageBySubCompanyId")
	@PermsCode("sick:subScribe:sunCompany:list")
	@Transactional
	open fun getSubScribePageBySubCompanyId(@RequestBody vo: CustomerSubscribeLogSelectVo): ResponseBody {
		val subscribeLogPage = iWebCompanyDeptService.getSubscribeLogPage(vo)
		for(subLog in subscribeLogPage.records){
			iCustomerInfoService.getJoinInfoByCustomerId(subLog.customerId,subLog)

		}
		return returnSuccess(subscribeLogPage)
	}

	/**
	 * 分院 待定预约记录分页
	 */
	@PostMapping("getUndeterminedSubScribePageBySubCompanyId")
//	@PermsCode("sick:subScribe:sunCompany:undetermined:list")
	@Transactional
	open fun getUndeterminedSubScribePageBySubCompanyId(@RequestBody vo: CustomerSubscribeLogSelectVo): ResponseBody {
		vo.subLogType = TypeEnum.CUSTOMER_SUBSCRIBE_TYPE_UNDETERMINDED
		val subscribeLogPage = iWebCompanyDeptService.getSubscribeLogPage(vo)
		for(subLog in subscribeLogPage.records){
			iCustomerInfoService.getJoinInfoByCustomerId(subLog.customerId,subLog)
		}
		return returnSuccess(subscribeLogPage)
	}

	/**
	 * 分院 待定预约记录数量
	 */
	@GetMapping("getUndeterminedSubScribeCountBySubCompanyId")
//	@PermsCode("sick:subScribe:sunCompany:undetermined:list")
	@Transactional
	open fun getUndeterminedSubScribeCountBySubCompanyId(): ResponseBody {
		val customerSubscribeLogSelectVo = CustomerSubscribeLogSelectVo(
			subLogType = TypeEnum.CUSTOMER_SUBSCRIBE_TYPE_UNDETERMINDED
		)
//		customerSubscribeLogSelectVo.beforePlanDate = Date()
		return returnSuccess(
			iWebCompanyDeptService.getSubscribeLogCount(
				customerSubscribeLogSelectVo
			)
		)
	}

	/**
	 * 客户取消预约记录
	 */
	@PostMapping("/cancelSubscribeList")
	@Transactional
	open fun cancelSubscribeList(@RequestBody vo: CustomerSubscribeLogSelectVo): ResponseBody {
		log.info("取消预约参数{}", vo)
		vo.subCompanyId = getContext().subCompanyId
		val cancelSubscribePage = iWebCompanyDeptService.cancelSubscribePage(vo)

		for(subLog in cancelSubscribePage.records){
			iCustomerInfoService.getJoinInfoByCustomerId(subLog.customerId,subLog)
		}
		return returnSuccess(cancelSubscribePage)
	}

	/**
	 * 客户预约记录
	 */
	@PostMapping("/getCustomerSubscribeLogPage")
	@Transactional
	open fun getCustomerSubscribeLogPage(@RequestBody vo: CustomerSubscribeLogSelectVo): ResponseBody {
		log.info("取消预约参数{}", vo)
		val cancelSubscribePage = iCustomerInfoService.getCustomerSubscribeLogPage(vo)
		for(subLog in cancelSubscribePage.records){
			iCustomerInfoService.getJoinInfoByCustomerId(subLog.customerId,subLog)
		}
		return returnSuccess(cancelSubscribePage)
	}

	/**
	 * 客户取消预约数量
	 */
	@GetMapping("/cancelSubscribeCount")
	@Transactional
	open fun cancelSubscribeCount(): ResponseBody {
		log.info("客户取消预约数量")
		return returnSuccess(
			iWebCompanyDeptService.getSubscribeLogCount(
				CustomerSubscribeLogSelectVo(
					status = Status.CANCEL,
					subLogType = TypeEnum.CUSTOMER_SUBSCRIBE_TYPE_NORMAL,
					cancelDay = Date()
				)
			)
		)
	}

	/**
	 * 取消预约
	 */
	@PostMapping("cancelLog")
	@Transactional(rollbackFor = [Exception::class])
	@PermsCode("customer:subscribe:cancel")
	open fun cancelLog(@RequestBody vo: CustomerSubscribeLogOperationVo): ResponseBody {
		val cancelLog = iCustomerSubscribeLogService.cancelLog(vo)
		if (cancelLog.bodyIsError()) {
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly()
			return cancelLog
		}
		val recordsDetailBySubscribeId = iCustomerSubscribeLogService.getRecordsDetailBySubscribeId(vo.id)
		if(recordsDetailBySubscribeId != null){
			val cancelRecordDetail = iSickMedicalRecordsService.onlyCancelRecordDetail(recordsDetailBySubscribeId.id)
			if(cancelRecordDetail.bodyIsError()){
				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly()
				return cancelRecordDetail
			}
		}
		return returnSuccess()
	}

	/**
	 * 确认用户会来
	 */
	@PostMapping("userCanComing/{id}")
	@Transactional(rollbackFor = [Exception::class])
	open fun userCanComing(@PathVariable id: Long): ResponseBody {
		var recordsDetail= iCustomerSubscribeLogService.getRecordsDetailBySubscribeId(id)
		if(recordsDetail == null ){
			val subLogToRecordsDetail = iCustomerSubscribeLogService.subLogToRecordsDetail(id)
			if (subLogToRecordsDetail.bodyIsError()) {
				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly()
				return subLogToRecordsDetail
			}
			recordsDetail= iCustomerSubscribeLogService.getRecordsDetailBySubscribeId(id)
		}
		val customerCanCome = iSickMedicalRecordsService.customerCanCome(recordsDetail!!.id)
		if (customerCanCome.bodyIsError()) {
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly()
			return customerCanCome
		}
		val completeLog = iCustomerSubscribeLogService.completeLog(CustomerSubscribeLogOperationVo(id))
		if (completeLog.bodyIsError()) {
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly()
			return completeLog
		}
		return returnSuccess()
	}

	/**
	 * 查询修改日志
	 */
	@GetMapping("getUpdateLogById/{id}")
	@Transactional(rollbackFor = [Exception::class])
	open fun getUpdateLogById(@PathVariable id:Long):ResponseBody{
		return returnSuccess(iCustomerSubscribeLogService.getSubscribeLogOperationLog(id))
	}

	/**
	 * map 时间-显示样式 格式
	 */
	private fun timeMap(min: Int, show: String): Map<String, Any> {
		val mutableMapOf = mutableMapOf<String, Any>()
		mutableMapOf["id"] = min
		mutableMapOf["name"] = show
		return mutableMapOf
	}

}
